import { View, Text, Picker } from "@tarojs/components"
import React, { useEffect, useMemo, useState } from "react"
import moment from "moment"
import { MoneyFormat } from "@/utils/format"
import http from "@/request"
import account from "@/store/account"
import Page from "@/components/page"
import BarChart from "./barChart"
import PageNav from "@/components/pageNav"
import Taro from "@tarojs/taro"
import CountryMap from "./countryMap"
import Modal from "./modal"
import "./index.scss"

const countryIncomeRate = (x) => {
    let rate = 0
    if (x < 0) {
        rate = 0
    } else if (x < 4000) {
        rate = -1.3333333333325912e-12 * x * x * x * x + 1.999999999999145e-8 * x * x * x - 0.00011166666666663058 * x * x + 0.28899999999993364 * x - 231.99999999995504
    } else if (x < 6000) {
        rate = 1.000000000000082e-9 * x * x * x - 0.00001750000000000117 * x * x + 0.10650000000000548 * x - 134.00000000000847
    } else if (x < 10000) {
        rate = -2.499999999999953e-7 * x * x + 0.005499999999999932 * x + 67.00000000000024
    } else {
        rate = -2.2083333333349992e-10 * x * x + 0.000057624999999996915 * x + 96.44583333333337
    }
    return rate > 100 ? 100 : rate < 0 ? 0 : Math.round(rate * 100) / 100
}

const Report: React.FC = () => {
    const [month, setMonth] = useState<string>('')
    const [monthData, setMonthData] = useState<{
        income?: number,
        expense?: number,
        month?: string
    }>({
        income: 0,
        expense: 0,
        month: moment().add(-1, 'month').format('YYYY-MM')
    })
    const [sysIncomeRate, setSysIncomeRate] = useState(0)
    const [sysExpenseRate, setSysExpenseRate] = useState(0)
    const [foodExpense, setFoodExpense] = useState(0)
    const [showEngel, setShowEngel] = useState(false)
    const [showCurMonGdp, setShowCurMonGdp] = useState(false)
    const [showCurYearGdp, setShowCurYearGdp] = useState(false)
    const [showMemberTip, setShowMemberTip] = useState(false)

    const queryData = () => {
        if (!month) return
        const day = moment(`${month}-01`)
        http.post(`/bills/statistics/category`, {
            startDate: day.startOf('month').format('YYYY-MM-DD'),
            endDate: day.endOf('month').format('YYYY-MM-DD'),
            accountId: account.activeAccount?.id
        }).then(res => {
            let foodPay = 0
            const resData = (res.data || []).reduce((obj, cur) => {
                // 食品、水果、烟酒饮料
                if ([1, 11, 16].includes(cur.category)) {
                    foodPay += cur.expense
                }
                return {
                    income: cur.income + obj.income,
                    expense: cur.expense + obj.expense,
                    month
                }
            }, {
                income: 0,
                expense: 0
            })
            setFoodExpense(foodPay)
            setMonthData(resData)
            if (memberNum) {
                queryRate(resData.income / memberNum, month, 1)
                queryRate(resData.expense / memberNum, month, 0)
            }
        })
    }

    const queryRate = (amount, month, type) => {        
        if (month && memberNum) {
            http.get('/bills/sysRate', { amount, month, type }).then(res => {
                if (type === 0) {
                    setSysExpenseRate(res.data || 0)
                } else {
                    setSysIncomeRate(res.data || 0)
                }
            })
        }
    }

    useEffect(() => {
        setMonth(moment().format('YYYY-MM'))
    }, [])

    useEffect(() => {
        queryData()
    }, [month])

    const memberNum = useMemo(() => {
        return (account.activeAccount?.members || []).filter(item => {
            // 过滤掉userId为0的公共收支
            return item.userId
        }).length
    }, [account.activeAccount])

    const incomeChartDatas = useMemo(() => {
        return [{
            name: '超过用户',
            value: sysIncomeRate
        }, {
            name: '超过全国',
            value: memberNum && countryIncomeRate((monthData.income || 0) / memberNum)
        }]
    }, [monthData, sysIncomeRate, memberNum])

    const expenseChartDatas = useMemo(() => {
        return [{
            name: '超过用户',
            value: sysExpenseRate
        }, {
            name: '超过全国',
            // 人均支出占收入比例（2023年）= 18175元 / 21691元 ≈ 83.8%
            value: memberNum && countryIncomeRate((monthData.expense || 0) / (0.683 * memberNum))
        }]
    }, [monthData, sysExpenseRate, memberNum])

    const yearsChange = (e) => {
        setMonth(e.detail.value)
    }

    const closeModal = () => {
        setShowCurMonGdp(false)
        setShowCurYearGdp(false)
        setShowEngel(false)
        setShowMemberTip(false)
    }

    const engelRate = useMemo(() => {
        return `${monthData.expense ? (Math.round(foodExpense * 10000 / monthData.expense) / 100).toFixed(2) : '-'}%`
    }, [foodExpense, monthData.expense])

    return (
        <Page className="report-page card-background text-main-color flex-column flex-item">
            <PageNav showBack className="report-page-header need-filter">
                <View className="picker-name flex-row flex-item">
                    <Text>报告月份：</Text>
                    <Picker mode='date'
                        value={month}
                        fields="month"
                        start={moment().add(-1, 'year').format('YYYY-MM')}
                        end={moment().format('YYYY-MM')}
                        onChange={yearsChange}>
                        <View className='picker'>
                            <Text>{month}</Text>
                            <Text className="iconfont icon-base-down"></Text>
                        </View>
                    </Picker>
                </View>
            </PageNav>
            <View className="page-body flex1">
                <View className="report-card page-background need-filter need-filter">
                    <View className="report-item font-size24">
                        <View className="report-item-title">统计账本</View>
                        <View className="account-name flex-row" onClick={() => setShowMemberTip(true)}>
                            <View className="report-item-val font-size40 flex1">{account.activeAccount?.name}</View>
                            <View className="flex1">
                                <Text>{memberNum}个成员</Text>
                                <Text className="iconfont icon-icon-question font-size32"></Text>
                            </View>
                        </View>
                    </View>
                    <View className="flex-row">
                        <View className="report-item font-size24 flex1">
                            <View className="report-item-title">本月收入</View>
                            <View className="report-item-val font-size40">{MoneyFormat(monthData.income)}</View>
                        </View>
                        <View className="report-item font-size24 flex1">
                            <View className="report-item-title">人均</View>
                            <View className="report-item-val font-size40">{MoneyFormat((monthData.income || 0) / memberNum)}</View>
                        </View>
                    </View>
                    <BarChart list={incomeChartDatas}></BarChart>
                    <View className="flex-row">
                        <View className="report-item font-size24 flex1">
                            <View className="report-item-title">本月支出</View>
                            <View className="report-item-val font-size40">{MoneyFormat(monthData.expense)}</View>
                        </View>
                        <View className="report-item font-size24 flex1">
                            <View className="report-item-title">人均</View>
                            <View className="report-item-val font-size40">{MoneyFormat((monthData.expense || 0) / memberNum)}</View>
                        </View>
                    </View>
                    <BarChart list={expenseChartDatas}></BarChart>
                    <View className="report-item font-size24">
                        <View className="flex-row flex1">
                            <View className="report-val-title flex1">
                                <View className="flex-row flex-item" onClick={() => setShowCurMonGdp(true)}>
                                    <Text>本月GDP约为</Text>
                                    <Text className="iconfont icon-icon-question font-size32"></Text>
                                </View>
                                <View className="report-item-val font-size40">${MoneyFormat((monthData.income || 0) / (0.43 * 7.122 * memberNum))}</View>
                            </View>
                            <View className="report-val-title flex1">
                                <View className="flex-row flex-item" onClick={() => setShowCurYearGdp(true)}>
                                    <Text>年GDP预计</Text>
                                    <Text className="iconfont icon-icon-question font-size32"></Text>
                                </View>
                                <View className="report-item-val font-size40">${MoneyFormat((monthData.income || 0) * 12 / (0.43 * 7.122 * memberNum))}</View>
                            </View>
                        </View>
                        <View className="report-val-title">与以下国家接近</View>
                        <View className="flex-column">
                            <CountryMap gdp={(monthData.income || 0) * 12 / (0.43 * 7.122 * memberNum)}></CountryMap>
                        </View>
                    </View>
                    <View className="report-item font-size24">
                        <View className="report-item-title flex-row flex-item" onClick={() => setShowEngel(true)}>
                            <Text>恩格尔系数</Text>
                            <Text className="iconfont icon-icon-question font-size32"></Text>
                        </View>
                        <View className="report-item-val font-size40">{engelRate}</View>
                        <View className="engel-progress-container font-size16 flex-row">
                            <View className="engel-progress-bar flex-row">
                                <View style={{ width: engelRate }}></View>
                                <View className="iconfont icon-sanjiaoxing"></View>
                                <View className="flex1"></View>
                            </View>
                            <View className="engel-progress-val flex0_30">
                                <View>极度富裕</View>
                                <View>0~30</View>
                            </View>
                            <View className="engel-progress-val flex30_40">
                                <View>富裕</View>
                                <View>30~40</View>
                            </View>
                            <View className="engel-progress-val flex40_50">
                                <View>小康</View>
                                <View>40~50</View>
                            </View>
                            <View className="engel-progress-val flex50_60">
                                <View>温饱</View>
                                <View>50~60</View>
                            </View>
                            <View className="engel-progress-val flex60_100">
                                <View>贫困</View>
                                <View>60~100</View>
                            </View>
                        </View>
                        <View className="report-val-title">与以下国家接近</View>
                        <View className="flex-column">
                            <CountryMap engel={monthData.expense ? Math.round(foodExpense * 10000 / monthData.expense) / 100 : 0}></CountryMap>
                        </View>
                    </View>
                </View>
            </View>
            <Modal
                visible={showCurMonGdp || showCurYearGdp || showEngel || showMemberTip}
                title="数值说明"
                onClose={closeModal}
                onSure={closeModal}>
                <View className="modal-body">
                    {showCurMonGdp ? <View className="tip-Text">
                        本月GDP计算方式为：本月人均收入÷（国内2023年度收入与GDP的比值 * 人民币与美元的汇率）
                    </View> : null}
                    {showCurYearGdp ? <View>
                        <View className="tip-Text">
                            年度GDP计算方式为：本月GDP * 12，可用于与其他国家、地区横向对比本月的收入水平
                        </View>
                        <View className="tip-Text">
                            本系统中，各个国家的GDP统计的年份为2023年，数据来源为世界银行2024年6月30日发布
                        </View>
                    </View> : null}
                    {showEngel ? <View>
                        <View className="tip-Text">
                            恩格尔系数的计算方法为：（餐饮食品 + 烟酒饮料 + 水果甜食等分类） ÷ 本月支出，自定义的分类不会计入分子
                        </View>
                        <View className="tip-Text">
                            一般来说该系数与财富的对应关系为：60~100贫困，50~60温饱，40~50小康，30~40富裕，小于30极其富裕
                        </View>
                        <View className="tip-Text">
                            由于各个国家对于恩格尔系数统计口径、统计年份有差异，个人的该系数与各个国家对比时误差会比较大
                        </View>
                    </View> : null}
                    {
                        showMemberTip ? <View className="tip-Text">
                            成员不包含公共收支成员（因为其仅存在财务概念上，不是实体的人）
                        </View> :
                            <View className="tip-Text">
                                注意：本数值为估算值，仅供参考
                            </View>
                    }
                </View>
            </Modal>
        </Page>
    )
}
export default Report